<?php
defined('SYS_RUN') or exit();

class Template {

    const DIR_TEMPLATE = 'view/template/';

    const PATTERN_TEMPLATE = '%s.php';

    public function render($template, $params = null, $returnHtml = false) {
        if($returnHtml)
            return $this->_fetch($this->_getTemplateFile($template), $params);
        else {
            $this->_display($this->_getTemplateFile($template), $params);
            return true;
        }
    }

    private function _getTemplateFile($template) {
        $templateFile = DIR_APPLICATION.self::DIR_TEMPLATE.sprintf(self::PATTERN_TEMPLATE, $template);
        if(!file_exists($templateFile))
            Error::trigger('Template file not found:'. $templateFile);
        return $templateFile;
    }

    private function _display($file, $params = null) {
        if($params) extract($params);
        include $file;
    }

    private function _fetch($file, $params = null) {
        ob_start();
        $this->_display($file, $params);
        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }
}